package com.javaweb.web.controller;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import jakarta.servlet.http.HttpServletResponse;

@RestController
public class TestController {

	private final ExecutorService executor = Executors.newCachedThreadPool();

	private final String[] data = {"密文下载中...","密文下载完成","解密中...","解密完成","入库中...","入库完成"};
	
	/** vue2代码示例：
	startStream() {
	  if (this.eventSource) {
	    this.eventSource.close()
	  }
	  this.content = '任务执行开始...\n'
	  this.eventSource = new EventSource('http://192.168.1.0:8002/JavaWebAdmin/streamResponseTest')
	  this.eventSource.onopen = () => {
	    console.log('连接已建立')
	  }
	  this.eventSource.onmessage = (event) => {
	    const data = event.data
	    console.log(data)
	    if (data === 'over') {
	      this.eventSource.close()
	      this.content += '任务执行完成\n'
	    } else {
	      this.content += event.data + '\n'
	    }
	  }
	  this.eventSource.onerror = (error) => {
	    console.error('EventSource 错误:', error)
	  }
	}
	*/
	@GetMapping(value ="/streamResponseTest", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	public ResponseBodyEmitter streamResponseTest(HttpServletResponse response) {
		response.setContentType("text/event-stream;charset=UTF-8");
	    ResponseBodyEmitter emitter = new ResponseBodyEmitter();
	    executor.execute(() -> {
	        try {
	        	/**
	            for (int i = 0; i < 10; i++) {
	                String chunk = "data: 正在模拟AI对话输出：" + UUID.randomUUID().toString() + "\n\n";
	                emitter.send(chunk);
	                Thread.sleep(1000);
	            }
	            */
	        	for(int i=0;i<data.length;i++){
	        		String chunk = "data: " + data[i] + "\n\n";
	        		if(i%2==0){
	        			Thread.sleep(5*1000);
	        		}
        			emitter.send(chunk);
	        	}
	            emitter.send("data: over\n\n");
	            emitter.complete();
	        } catch (Exception e) {
	            emitter.completeWithError(e);
	        }
	    });
	    return emitter;
	}
	
	//分页（分批次）查询数据并分批次写入
	@GetMapping("/batchDownloadTest")
	public ResponseEntity<StreamingResponseBody> batchDownload(HttpServletResponse response) {
	    StreamingResponseBody stream = outputStream -> {
	        for (int i = 0; i < 1_000_000; i++) {
	            outputStream.write((UUID.randomUUID() + "\r").getBytes(StandardCharsets.UTF_8));
	        }
	        outputStream.flush();
	    };
	    HttpHeaders headers = new HttpHeaders();
	    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=1.txt");
	    return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(stream);
	}
	
}
